package com.mymall.product.service.impl;

import lombok.val;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mymall.common.utils.PageUtils;
import com.mymall.common.utils.Query;;

import com.mymall.product.dao.CategoryDao;
import com.mymall.product.entity.CategoryEntity;
import com.mymall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> queryTreeList() {

        // 第一步查询出所有的目录信息
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        // 将结果分类
//        List<CategoryEntity> collect = categoryEntities.stream()
//                .filter(a -> a.getParentCid() == 0)
//                .map(a->{
//                    a.setChildCategory(groupList(a.getCatId(),categoryEntities));
//                    return a;
//                })
//                .collect(Collectors.toList());


        return groupList(0L,categoryEntities);
    }

    @Override
    public void batchRemoveByIds(List<Long> longs) {


        // TODO 1 检查项目是否又被别人引用，如果有就不能删除。

        // 删除数据
        baseMapper.deleteBatchIds(longs);

    }

    private List<CategoryEntity> groupList(Long parentId,List<CategoryEntity> categoryEntities){
        return categoryEntities.stream()
                .filter(a -> a.getParentCid() == parentId)
                .map(a->{
                    a.setChildCategory(groupList(a.getCatId(),categoryEntities));
                    return a;
                })
                .sorted((a,b)->
                    Integer.compare(a.getSort()==null?0:a.getSort(),b.getSort()==null?0:b.getSort())
                )
                .collect(Collectors.toList());
    }

}
